import defAva from '@/assets/images/Layout/Avatar/profile.jpg'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref(getToken());

    const id = ref("");

    const name = ref("");

    const avatar = ref("");

    const roles = ref<string[]>([]);

    const permissions = ref<string[]>([]);

    /** 登录 */
    function login(userInfo: LoginFormRecord) {
      userInfo.username = userInfo.username.trim()
      return loginApi(userInfo).then(res => {
        setToken(res.token)
        token.value = res.token
        return "";
      })
    }

    /** 获取用户信息 */
    function getInfo() {
      return getInfoApi().then(res => {
        const user = res.user

        const avatarUrl = !user.avatar ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          roles.value = user.roles
          permissions.value = res.permissions
        } else {
          roles.value = ['ROLE_DEFAULT']
        }
        id.value = user.userId
        name.value = user.userName
        avatar.value = avatarUrl
        return res
      })
    }

    /** 退出系统 */
    function logOut() {
      return logoutApi(token.value).then(() => {
        token.value = ''
        roles.value = []
        permissions.value = []
        removeToken()
        return "";
      }).catch(err => {
        token.value = ''
        roles.value = []
        permissions.value = []
        removeToken()
        return "";
      })
    }

    return { token, id, name, avatar, roles, permissions, login, getInfo, logOut }
  }
)

